"""The XMLHandler module contains the VideoList class, which handles XML lookups and edits."""

import xml.etree.cElementTree as et

class VideoList:
    """The VideoList class handles XML lookups and edits. Takes an XML filename as an argument"""

    def __init__(self, xmlfile):
        if xmlfile == "":
            self.root = et.Element("filelist")
            self.root.attrib["version"] = "PLGEN_XMLHandler_0.1"
        else:
            tree = et.parse(xmlfile)
            self.root = tree.getroot()
        self.fileMatchList = []

    def getList(self):
        list = []
        for node in self.root:
            filename = node.find("filename").text
            item = {'folder': node.find("folder").text,
                    'filename': filename,
                    'tags': node.find("tags").text.split(';'),
                    'rating': node.find("rating").text}
            list.append(item)
            self.fileMatchList.append((filename,node))
        return list

    def updateAndSaveList(self, list, listfilename):
        for item in list:
            if item.has_key("action"):
                if item["action"] == "update":
                    for fm in self.fileMatchList:
                        if fm[0] == item["filename"]:
                            self.updateItem(fm[1], item)
                            break
                elif item["action"] == "new":
                    self.addItem(item)
        self.saveList(listfilename)

    def updateItem(self, oldItem, newItem):
        newItem.pop("action")
        for key in newItem.keys():
            node.find(key).text = newItem[key]

    def addItem(self, item):
        item.pop("action")
        listItem = et.SubElement(self.root, "file")

        keys = self.reorderKeys(item.keys())

        for key in keys:
            tag = et.SubElement(listItem, key)
            tag.text = item[key]

    def saveList(self, listfilename):
        tree = et.ElementTree(self.root)
        tree.write(listfilename)


    def reorderKeys(self, keys):
        preflist = ["filename", "folder", "tags", "rating"]
        retList = []
        for key in preflist:
            if key in keys:
                retList.append(key)
                keys.remove(key)
        retList.append(keys)

        #This is a hacky solution. Please replace
        retList.remove([])
        #End hack

        return retList

class Settings:
    def __init__(self):
        tree = et.parse("settings.xml")
        self.root = tree.getroot()

        # TODO: Actually read the settings
        self.settings = {"exportFormats": ["Media Player Classic", "PowerDVD"],
                         "wildcards": {"all": "All files (*.*)|*.*",
                                       "Media Player Classic": "MPC Playlist (*.mpcpl)|*.mpcpl",
                                       "PowerDVD": "PowerDVD Playlist (*.pls)|*.pls"},
                         "ratings": ["1", "2", "3", "4", "5"],
                         "defaultList": "default.xml"
                         }

    def getSettings(self):
        return self.settings